package com.example.download;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/downServlet")
public class downServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");
        //1.用getParameter获得filename
        ServletContext context = this.getServletContext();
        String path = context.getRealPath("/image/" + filename);
        //2.获得filename的真实地址
        InputStream fileInputStream = new FileInputStream(path);
        //3.通过文件输入流建立 InputStream对象
        String mimeType = context.getMimeType(filename);
//        4.ServleContext对象的getMimeType获得mime
        response.setHeader("content-type",mimeType);
        response.setHeader("content-disposition","attachment;filename="+filename);
//        5.改变响应头信息
        ServletOutputStream outputStream = response.getOutputStream();
//        6.用ServletOutputStream输出字节码文件
        byte[] buff = new byte[1024*8];
        int len = 0;
        while ((len = fileInputStream.read(buff))!= -1){
            outputStream.write(buff,0,len);
        }
        fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
